#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating new user account
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file


import accoufer
import shelve
import cgi 

def run():
    # extract parameters
    form = cgi.FieldStorage()
    if "login" not in form:
        header = 'Set-Cookie: user=; expires=Thu, 2 Aug 2001 00:00:00 UTC; path=%s'
        print accoufer.HTML_HEADER%(accoufer.logoutHeader(), "Login", FORM)
        return 
    try:
        login = form["login"].value
        pwd = form["pwd"].value
    except KeyError:
        return error("Invalid parameters")

    #check password
    users = shelve.open(accoufer.USER_PATH)
    try:
        user = users[login]
    except KeyError:
       return error("User not found")
    if accoufer.md5(pwd).digest() != user[accoufer.USER_PWD]:
       return error("Bad password")
 
    # output message
    header = accoufer.cookieHeader(login)
    msg =  SUCCES%login
    print accoufer.HTML_HEADER%(header, "User created", msg )

  

def error(txt):
    
    msg = ERROR%txt
    print accoufer.HTML%("Error", msg)


SUCCES = """<h1>login</h1>User "%s" successfully logged.<p/><hr/> <a href="./index.html">Start</a>"""

INFORM = """<form method=post action="./xlogin">
Login: <input name="login" /><br/>
Password: <input type="password" name="pwd" /><br/>
<input type="submit" value="Run"/></form><p/>
<a href="./xnewuser">New user</a>
"""

ERROR = "<h1>login</h1><b>%s</b><p/>"+INFORM

FORM = "<h1>login</h1>"+INFORM

if __name__=="__main__":
    run()

